package org.laokouyun.demo;
import io.grpc.ManagedChannel;
import io.grpc.NameResolverRegistry;
import io.grpc.StatusException;
import lombok.RequiredArgsConstructor;
import org.laokouyun.demo.discovery.DiscoveryNameResolverProvider;
import org.laokouyun.demo.proto.HelloWorldProto;
import org.laokouyun.demo.proto.SimpleGrpc;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.grpc.client.GrpcChannelFactory;
import org.springframework.grpc.client.GrpcClientFactory;

import java.time.Duration;

@EnableConfigurationProperties
@EnableDiscoveryClient
@RequiredArgsConstructor
@SpringBootApplication(scanBasePackages = "org.laokouyun.**")
public class ServerDemoApplication implements CommandLineRunner {

    private final GpcClientUtils gpcClientUtils;
    private final GrpcChannelFactory grpcChannelFactory;
    private final DiscoveryClient discoveryClient;
    private final GrpcClientFactory grpcClientFactory;
    private final DiscoveryNameResolverProvider discoveryNameResolverProvider;

    static void main(String[] args) {
        SpringApplication.run(ServerDemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws InterruptedException, StatusException {
        // test();
        Thread.sleep(Duration.ofSeconds(10));
        NameResolverRegistry.getDefaultRegistry().register(discoveryNameResolverProvider);
        HelloWorldProto.HelloRequest request = HelloWorldProto.HelloRequest.newBuilder().setName("test").build();
        SimpleGrpc.SimpleBlockingV2Stub stub = grpcClientFactory.getClient("discovery://server-demo", SimpleGrpc.SimpleBlockingV2Stub.class, null);
        System.out.println(stub.sayHello(request));
        System.out.println(stub.sayHello(request));
        System.out.println(stub.sayHello(request));
        System.out.println(stub.sayHello(request));
    }

//    public void test() throws Exception {
//        Thread.sleep(Duration.ofSeconds(10));
//        for (int i = 0; i < 10; i++) {
//            System.out.println(gpcClientUtils.invoke("server-demo", SimpleGrpc.SimpleBlockingV2Stub.class, "sayHello", HelloWorldProto.HelloRequest.class, request));
//        }
//    }

}
